/*
 * @lc app=leetcode.cn id=1028 lang=cpp
 *
 * [1028] 从先序遍历还原二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    TreeNode *recoverFromPreorder(string traversal)
    {
        int i = 0, deep, num;
        stack<TreeNode *> stk;
        TreeNode *node;

        while (traversal[i])
        {
            deep = num = 0;
            while (traversal[i] == '-')
            {
                i++;
                deep++;
            }
            while (traversal[i] != '-' && traversal[i])
            {
                num = num * 10 + (traversal[i] - '0');
                i++;
            }
            while (stk.size() > deep)
            {
                stk.pop();
            }
            node = new TreeNode(num);
            if (!stk.empty())
            {
                if (stk.top()->left == NULL)
                {
                    stk.top()->left = node;
                }
                else
                {
                    stk.top()->right = node;
                }
            }
            stk.push(node);
        }
        // 取出栈底元素
        while (!stk.empty())
        {
            node = stk.top();
            stk.pop();
        }

        return node;
    }
};
// @lc code=end
